<?php
namespace Common\Model;
use Common\Model\BaseModel;
/**
 * 权限规则model
 */
class IndexModel extends BaseModel{


	/**
	 * 初始化
	 */
	public function __construct(){

	}

	/**
	 * 首页
	 */
	public function setting($mail_template){

		$post = I('post.');

		$old_password = md5(md5(trim($post['old_password']))."Yumcms.org");

		$where["id"] = array("eq",session('user.id'));
		$where['password'] = array("eq",$old_password);

		$user_info = M('users')->where($where)->find();

		if(!empty($user_info)){

			//新密码修改
			if(!empty($post['new_password'])){

				if(preg_match('/^\d+$/',$post['new_password']) || (strlen($post['new_password']) < 6) || (strlen($post['new_password']) > 6)){
					$data['new_password_code'] = 400;
					$data['new_password_msg'] = "新密码不符合要求";
				}else{
					$new_password = md5(md5(trim($post['new_password']))."Yumcms.org");
					if(!empty($new_password)){
						$items['password'] = $new_password;
						//密码修改成功
						$data['password_code'] = 200;
						$data['password_msg'] = "恭喜，您的密码已修改成功！";
					}
				}
			}

			//邮箱修改
			if(!empty($post['new_email'])){

				if(preg_match('/^(?:[a-z0-9]+[_\-+.]?)*[a-z0-9]+@(?:([a-z0-9]+-?)*[a-z0-9]+.)+([a-z]{2,})+$/i',$post['new_email'])){

					$map['id'] = array("neq",$user_info['id']);
					$map['email'] = array("eq",$post['new_email']);

					$is_mail = M('users')->where($map)->find();

					if(empty($is_mail)){

						//邮件发送
						$link = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Admin/confirm_email',array($user_info['id']=>$user_info['email_code']));

						$content = preg_replace(array('/(__username__)/','/(__link__)/'),array($user_info['username'],$link),$mail_template);

						send_email($post['new_email'],"修改邮箱-Yuncms.org",$content);

						$items['email_new'] = $post['new_email'];
						$data['mail_code'] = 200;
						$data['mail_msg'] = "新的激活邮件已发送到您的邮箱中，请前往邮箱进行查收！";
					}else{
						//新邮箱已被使用,请更换邮箱!
						$data['mail_code'] = 400;
						$data['mail_msg'] = "新邮箱已被使用,请更换邮箱!";
					}

				}else{
					$data['mail_code'] = 401;
					$data['mail_msg'] = "邮箱格式错误!";
				}

			}else{
				$data['mail_code'] = 201;
			}

			//手机号修改
			if(!empty($post['new_mobile'])){
				if(preg_match('/^1[3-9]\d{9}$/i',$post['new_mobile'])){
					$items['phone'] = $post['new_mobile'];
					$data['phone_code'] = 200;
				}else{
					$data['phone_code'] = 400;
					$data['phone_msg'] = "手机格式错误";
				}
			}else{
				$data['phone_code'] = 201;
			}

			//QQ客服
			if(!empty($post['qq'])){
				if(preg_match('/^[0-9]*$/i',$post['qq'])){
					$items['qq'] = $post['qq'];
					$data['qq_code'] = 200;
				}else{
					$data['qq_code'] = 400;
					$data['qq_msg'] = "QQ客服格式错误";
				}
			}else{
				$data['qq_code'] = 201;
			}

			M("users")->where($where)->setField($items);
		}else{

			$data['password_code'] = 400;
			$data['password_msg'] = "原密码错误，请重新输入！";
		}

		return $data;

	}


}
